package com.secsbrain.deploy.biz.utils;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * URL工具类
 *
 * @author zhaoyi
 */
public class UrlUtil {
    
    public static final String ENCODING="UTF-8";

    /**
     * 将 String 转为 map
     * 
     * @param param aa=11&bb=22&cc=33
     * @return
     */
    public static Map<String, Object> getUrlParams(String param) {
        Map<String, Object> map = new HashMap<String, Object>();
        if ("".equals(param) || null == param) {
            return map;
        }
        String[] params = param.split("&");
        for (int i = 0; i < params.length; i++) {
            String[] p = params[i].split("=");
            if (p.length == 2) {
                map.put(p[0], p[1]);
            }
        }
        return map;
    }
   
    /**
     * 将map 转为 string
     * 
     * @param map
     * @return
     * @throws Exception 
     */
    public static String getUrlParamsByMap(Map<String, Object> map,
            boolean isSort) throws Exception {
        if (map == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        List<String> keys = new ArrayList<String>(map.keySet());
        if (isSort) {
            Collections.sort(keys);
        }
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            if(!map.containsKey(key)||map.get(key)==null){
                continue;
            }
            String value = map.get(key).toString();
            sb.append(key + "=" + URLEncoder.encode(value,ENCODING));
            sb.append("&");
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = s.substring(0, s.lastIndexOf("&"));
        }
        return s;
    }
    
}
